package com.bq.gametrade.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bq.gametrade.HttpLink;
import com.bq.gametrade.R;
import com.bq.gametrade.adapter.FriendListAdapter;
import com.bq.gametrade.base.BaseFragment;
import com.bq.gametrade.bean.FriendsList;
import com.bq.gametrade.bean.FriendsListDetails;
import com.bq.gametrade.http.VRHttp;
import com.bq.gametrade.http.VRHttpListener;
import com.bq.gametrade.ui.activity.AddressBookActivity;
import com.bq.gametrade.ui.activity.FriendInformationActivity;
import com.bq.gametrade.ui.activity.LoginActivity;
import com.bq.gametrade.ui.activity.MainActivity;
import com.bq.gametrade.utils.Base64Util;
import com.bq.gametrade.utils.SharedPreferencesUtils;
import com.bq.gametrade.utils.ToastUtils;
import com.bq.gametrade.widget.PromptAlertDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Feel on 2017/1/4.
 */

public class FriendFragment extends BaseFragment {

    private ImageView ivService;
    private LinearLayout layPrompt;
    private TextView tvPormpt;
    private ListView listView;
    private ArrayList<FriendsListDetails> mList = new ArrayList<>();
    private FriendListAdapter adapter;
    private MainActivity activity;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = (MainActivity) getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_friend, container, false);
        initView(root);
        return root;
    }

    private void initView(View view) {
        ivService = (ImageView) view.findViewById(R.id.iv_userService);
        ivService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), AddressBookActivity.class));
            }
        });
        tvPormpt = (TextView) view.findViewById(R.id.tv_pormpt);
        layPrompt = (LinearLayout) view.findViewById(R.id.lay_prompt);
        listView = (ListView) view.findViewById(R.id.lv_friend);
        adapter = new FriendListAdapter(getActivity(), mList);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(mList.size()>0){


                String name;
                if (!mList.get(position).userName.equals("")) {
                    name = mList.get(position).userName;
                } else {
                    name = "还没有昵称";
                }
                Intent intent = new Intent(getActivity(), FriendInformationActivity.class);
                intent.putExtra("friendAccount", mList.get(position).f_userId);
                intent.putExtra("strFriendHeadImage", mList.get(position).headimg);
                intent.putExtra("friendName", name);
                intent.putExtra("friendBqAccount", mList.get(position).bqAccount);
                intent.putExtra("friendNote", mList.get(position).remark);
                startActivity(intent);
                }
            }
        });
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                if(mList.size()>0){
                    new PromptAlertDialog(getActivity()).builder().setTitle("提示").setTouchOutsideCanceled(true)
                            .setMsg("您确定删除好友吗！")
                            .setPositiveButton("删除", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    deleteFriend(mList.get(position).f_userId);
                                }
                            }).setNegativeButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    }).show();
                }
                return true;
            }
        });

    }


    @Override
    public void onResume() {
        super.onResume();
        if (application.isLogin()) {
            getFriendInfo();
        } else {
            mList.clear();
            tvPormpt.setText("您还没有登陆哦！");
            tvPormpt.setVisibility(View.VISIBLE);
            layPrompt.setVisibility(View.VISIBLE);
        }
    }


    private List<String> friends = new ArrayList<>();
    private void getFriendInfo() {

        Map<String, String> params = new HashMap<>();
        params.put("token", application.getUserInfo().token);
        VRHttp.getMyFriendList(getActivity(), HttpLink.FRIEND_LIST_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                closeSpotsDialog();
                if (response != null) {
                    FriendsList userFriend = (FriendsList) response;
                    if (userFriend.status.equals("0")) {
                        mList = userFriend.friend_list;
                        if (mList.size() > 0) {
                            listView.setVisibility(View.VISIBLE);
                            layPrompt.setVisibility(View.GONE);
                            friends.clear();
                            for (int i=0;i<mList.size();i++){
                                friends.add(mList.get(i).f_userId);
                            }
                            SharedPreferencesUtils.saveValue(getActivity(),SharedPreferencesUtils.friend_lists,friends.toString().replace("[","").replace("]",""));
                            adapter.setData(mList);
                            adapter.notifyDataSetChanged();
                        } else {
                            mList.clear();
                            adapter.notifyDataSetChanged();
                            listView.setVisibility(View.INVISIBLE);
                            layPrompt.setVisibility(View.VISIBLE);
                            layPrompt.setVisibility(View.VISIBLE);
                            tvPormpt.setVisibility(View.VISIBLE);
                            tvPormpt.setText("您还没有好友哦!快去邀请吧");
                        }
                    } else if (userFriend.status.equals("99")) {
                        ToastUtils.showToast(getActivity(), "登录超时");
                        application.setUserInfo(null);
                        startActivity(new Intent(getActivity(), LoginActivity.class));
                    } else if (userFriend.status.equals("98")) {
                        ToastUtils.showToast(getActivity(), "您的账号已在其它设备登录，请重新登录修改您的密码");
                        application.setUserInfo(null);
                        startActivity(new Intent(getActivity(), LoginActivity.class));
                    }
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeSpotsDialog();
            }
        });
    }


    private void deleteFriend(String friendAccount) {
        Map<String, String> params = new HashMap<>();
        params.put("token", application.getUserInfo().token);
        params.put("friendId", friendAccount);
        showSpotsDialog("正在删除···");
        VRHttp.getResponse(getActivity(), HttpLink.FRIEND_DELETE_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                if(response != null){
                    try {
                        JSONObject object = new JSONObject(response.toString());
                        String status = object.getString("status");
                        String message = object.getString("message");
                        if(status.equals("0")){
                            SharedPreferencesUtils.saveValue(getActivity(),SharedPreferencesUtils.friend_lists,"");
                            ToastUtils.showToast(getActivity(),Base64Util.decodeStr(message));
                            getFriendInfo();
                        }else if(status.equals("1")){
                            ToastUtils.showToast(getActivity(),Base64Util.decodeStr(message));
                        }else if (status.equals("99")) {
                            ToastUtils.showToast(getActivity(),"登录超时请重新登陆");
                            application.setUserInfo(null);
                            startActivity(new Intent(getActivity(), LoginActivity.class));
                        } else if (status.equals("98")) {
                            ToastUtils.showToast(getActivity(),"您的账号已在其它设备登录，请重新登录修改您的密码");
                            application.setUserInfo(null);
                            startActivity(new Intent(getActivity(), LoginActivity.class));
                        } else {
                            ToastUtils.showToast(getActivity(),"删除友失败！");
                        }
                    }catch (JSONException e){
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeSpotsDialog();
            }
        });
    }
}
